<template>
	<view class="add-house-info">
		<view class="house-title">
			<view class="title">
				报修房屋
			</view>
			<view class="content">
				<u-cell
					:title="repairHouseList[0].name || '北京西三旗花园1号楼 101'"
					isLink
					:border="false"
					url=""
					@click="showPicker(1)"
				>
				</u-cell>
				
			</view>
		</view>
		<view class="houseOwner-info">
			<view class="title">
				报修信息
			</view>
			
			<u--form 
			  labelPosition="left"
			  :model="repairInfo"
			  :rules="rules"
			  ref="form1"
			  labelWidth="208rpx"
			  :borderBottom="false"
			  :labelStyle="{
				  backgroundColor: '#fff',
				  padding:'30rpx'
			  }">
				<u-form-item
					label="维修项目"
					prop="repairItemId"
					borderBottom
					@click="showPicker(2)"
				>
					<u--input
						v-model="repairItem"
						disabled
						disabledColor="#ffffff"
						placeholder="请选择维修项目"
						border="none"
					></u--input>
					<u-icon
						slot="right"
						name="arrow-right"
						:customStyle="{ marginRight: '28rpx', color: '#C3C3C5' }"
					></u-icon>
				</u-form-item>
				
				
				<!-- 手机号 -->
				<u-form-item
					label="手机号码"
					prop="mobile"
					borderBottom
				>
					<u--input
						v-model="repairInfo.mobile"
						border="none"
						type="number"
						placeholder="请输入联系手机号"
					></u--input>
					
				</u-form-item>
				
				<!-- 预约日期 -->
				<u-form-item
					label="预约日期"
					prop="appointment"
					borderBottom
					@click="showPicker(3)"
				>
					
					<u--input
						v-model="repairInfo.appointment"
						disabled
						disabledColor="#ffffff"
						placeholder="请选择上门维修日期"
						border="none"
					></u--input>
					<u-icon
						slot="right"
						name="arrow-right"
						:customStyle="{ marginRight: '28rpx', color: '#C3C3C5' }"
					></u-icon>
				</u-form-item>
				
				<!-- 问题描述 -->
				<u-form-item
					prop="description"
					borderBottom
					ref="item3"
				>
					<u-cell-group :border="false">
						<u-cell
							size="large"
							title="问题描述"
							class="text-cell"
							:border="false"
						>
							<u--textarea 
								slot="label" 
								v-model="repairInfo.description" 
								placeholder="请填写详细报修内容，有助于工作人员快速帮您解决问题。" 
								border="none"
								height="84rpx"
							>
							</u--textarea>
						</u-cell>
						
					</u-cell-group>
				</u-form-item>
				<u-form-item
					prop="attachment"
					:borderBottom="false"
					ref="item3"
				>
					<u-cell-group :border="false">
						<u-cell
							size="large"
							title="问题附件"
							:border="false"
						>
							<u-upload
								slot="label"
								uploadIcon="plus"
								:fileList="fileList1"
								@afterRead="afterRead"
								@delete="deletePic"
								name="1"
								multiple
								:maxCount="10"
							></u-upload>
						</u-cell>
					</u-cell-group>
				</u-form-item>
			</u--form>
			
			
		</view>
		
		
		<life-button icon="../../static/icon/check.png" @click="commitRepair" >提交报修</life-button>
		
		<!--  选择房屋 -->
		<u-action-sheet
			:show="show1"
			@close="show1 = false"
			:closeOnClickOverlay="true"
			cancelText="取消"
			title="选择报修房屋"
			:actions="repairHouseList"
			round="20rpx"
		>
		</u-action-sheet>
		
		<!--  选择维修项目 -->
		<u-action-sheet
			:show="show2"
			@close="show2 = false"
			:closeOnClickOverlay="true"
			cancelText="取消"
			title="选择保修项目"
			:actions="repairItemList"
			@select="selectClick"
			round="20rpx"
		>
		</u-action-sheet>
		
		<!-- 选择日期 -->
		<u-datetime-picker
			ref="datetimePicker"
			:show="show3"
		    v-model="date"
			mode="date"
			:closeOnClickOverlay="true"
			:formatter="formatter"
			@close="show3 = false"
			@cancel="show3 = false"
			@confirm="dateConfirm"
		>
		</u-datetime-picker>
	</view>
</template>

<script>
	import toast from '@/utils/toast.js'
	import { getRepairHouse, getRepairItem } from '@/api/add-repair.js'
	export default {
		data() {
			return {
				fileList1: [],
				show1: false,
				show2: false,
				show3: false,
				repairItemList: [],
				repairHouseList: [],
				repairInfo: {
					repairItemId: '',
					mobile: '',
					appointment: '',
					description: '',
					attachment: []
				},
				repairItem: '',
				date: Number(new Date()),
				rules: {
					repairItemId: {
						type: 'string',
						required: true,
						message: '请选择维修项目',
						trigger: ['blur', 'change']
					},
					mobile: [
						{
							required: true, 
							message: '请输入手机号',
							trigger: ['change','blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change','blur'],
						}
					],
					'appointment': {
						type: 'string',
						required: true,
						message: '请选择预约日期',
						trigger: ['change'],
					},
					description: [{
						required: true,
						message: '请输入问题描述',
						trigger: ['change', 'blur'],
					}]
				},
			}
		},
		
		// watch: {
		// 	IDcardPhoto: {
				
		// 	}
		// },
		
		methods: {
			
			// 确认选择维修项目
			selectClick(e) {
				console.log(e);
				this.repairItem = e.name
				this.repairInfo.repairItemId = e.id
			},
			
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			
			// 上传图片
			uploadFilePromise(url, name) {
				// 获取上传域名
				// const domain = this.loginForm.serveIp;
				// token
				console.log('store',this.$store.state.user);
				console.log('url', url);
				// let token = JSON.parse(uni.getStorageSync('userToken')).token
				let token = this.$store.state.user.userToken.token
				// 请求头
				var header = {
					Authorization: 'Bearer ' + token
				};
				
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						// 完整上传路径 H5端需要解决跨域问题
						url: 'https://live-api.itheima.net/upload',
						// 本地上传读取到的url
						filePath: url,
						name: 'file',
						// 请求头
						header: header,
						// 附加表单对象
						formData: {
							file: url
						},
						success: res => {
							console.log('suc', res);
							// 这里res是普通对象，但是res.data为JSON字符串，需要转一下
							const result = JSON.parse(res.data);
							
							// 获取上传成功后的文件地址
							const formUrl = result.data.url;
							const id = result.data.id
							
							// 赋值表单数据（后台需要）
							console.log(formUrl);
							// this.dataForm.picture = formUrl;
							this.repairInfo.attachment.push({
								id: id,
								url: formUrl
							})
							// this.repairInfo.attachment.url = formUrl
							
							// 把文件的二进制对象抛出去用于图片预览
							resolve(res.data.data);
						}
					});
				});
			},
			
			// 打开选择器
			showPicker(index) {
				this[`show${index}`] = true
			},
			
			// 格式化时间列表
			formatter(type, value) {
                if (type === 'year') {
                    return `${value}年`
                }
                if (type === 'month') {
                    return `${value}月`
                }
                if (type === 'day') {
                    return `${value}日`
                }
                return value
            },
			
			// 关闭日期选择器
			closePicker(num) {
				console.log('close',`show${num}`);
				this.show3 = false
				this[`show${num}`] = false
				// this.show + nums
			},
			
			// 确认时间选择器
			dateConfirm(e) { 
				console.log(e);
				// this[`this${}`]
				this.repairInfo.appointment = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				this.show3 = false
			},
			
			
			// 上传
			uploadFilePromise2(url, name) {
				// 获取上传域名
				// const domain = this.loginForm.serveIp;
				// token
				console.log('url', url);
				let token = uni.getStorageSync('userToken')
				// 请求头
				var header = {
					Authorization: 'Bearer ' + token
				};
				// 判断是否选择了租户ID
				// const TENANT_ID = getStore({ name: 'tenantId' });
				// 请求头中添加租户
				// if (TENANT_ID) {
				// 	header['TENANT-ID'] = TENANT_ID;
				// }
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						// 完整上传路径 H5端需要解决跨域问题
						url: 'https://live-api.itheima.net/upload',
						// 本地上传读取到的url
						filePath: url,
						name: 'file',
						// 请求头
						header: header,
						// 附加表单对象
						formData: {
							file: url
						},
						success: res => {
							console.log('suc', res);
							// 这里res是普通对象，但是res.data为JSON字符串，需要转一下
							const result = JSON.parse(res.data);
							
							// 获取上传成功后的文件地址
							const formUrl = result.data.url;
							
							// 赋值表单数据（后台需要）
							console.log(formUrl);
							// this.dataForm.picture = formUrl;
							this.IDcardPhoto.push({
								url: formUrl,
								name
							})
							
							// 把文件的二进制对象抛出去用于图片预览
							resolve(res.data.data);
						}
					});
				});
			},
			
			
			async commitRepair() { },
			
			// 获取我能报修的房间信息
			async getRepairHouse() {
				const res = await getRepairHouse()
				console.log('repairhouse',res);
				// let tempArr = []
				res.data.forEach(item => {
					this.repairHouseList.push(item)
				})
				// this.repairHouseList.push(res.data)
			},
			
			// 获取维修项目
			async getRepairItem() {
				const res = await getRepairItem()
				console.log('维修项目',res);
				// this.repairItemList.push(res.data)
				res.data.forEach(item => {
					this.repairItemList.push(item)
				})
			}
			
		},
		
		computed: {
			 
		},
		
		async onLoad(options) {
			console.log(options)
			this.getRepairHouse()
			this.getRepairItem()
			// console.log(options.title.split(' '));
			// const res = await getRepairHouse()
			// console.log('repairhouse',res);
		},
		
		onReady() {
			this.$refs.form1.setRules(this.rules)
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter)
		}
	}
</script>

<style lang="scss" scoped>
	.add-house-info {
		height: 100%;
		background-color: #FAFAFA;
		padding-bottom: 220rpx;

		.house-title {
			.title {
				padding: 30rpx;
				color: #979797;
				font-size: 24rpx;

			}

			.content {
				// padding: 30rpx;
				color: #333333;
				font-size: 28rpx;
				// line-height: 1.5;
				// letter-spacing: 0rpx;
				background-color: #fff;

			}
		}

		.houseOwner-info {
			.title {
				padding: 30rpx;
				color: #979797;
				font-size: 24rpx;
				// margin-bottom: 30rpx;
			}
		}
	}
	
	::v-deep .u-form-item__body {
		background-color: white;
		padding: 0 !important;
		// height: 102rpx;
	}
	
	::v-deep .u-form-item {
		background-color: white !important;
	}
	
	::v-deep .u-cell__body{ 
		// height: 102rpx;
		background-color: #fff;
		padding: 30rpx !important;
	}
	
	::v-deep .u-textarea {
		height: 750rpx;
		padding: 0 !important;
		margin-top: 20rpx;
		height: 84rpx
	}
	
	.text-cell {
		height: 206rpx !important; 
		background-color: #fff;
		padding: 30rpx !important;
	}
	
	
	.upload-title {
		background-color: white;
		margin-top: 30rpx;
		// padding-left: 30rpx;
		
		.upload-text-label {
			color: #C3C3C5;
			font-family: PingFang SC;
			font-weight: regular;
			font-size: 22rpx;
			line-height: 1.5;
			letter-spacing: 0rpx;
			text-align: left;
			margin-top: 12rpx
		}
	}
	
	
	::v-deep .u-upload {
		// background-color: red;
		margin-top: 20rpx;
		// padding-left: 30rpx !important;
		// padding-right: 30rpx;
		background-color: #fff;
		box-sizing: border-box;
	}
	
	::v-deep .u-upload__button {
		border: 0.5px solid #ddd;
		background-color: #fff !important;
	}
	
	.u-page {
		&__code-text {
			color: $u-primary;
			font-size: 15px;
		}
	}
	
	.u-demo-block__content {
		@include flex;
		margin-right: 50rpx;
	}
</style>
